<template>
  <div class="car-source-wrapper">
    <page-form-item class="mb-1" field="source" label="车辆来源" required size="1">
      <a-radio-group v-model="form.source">
        <a-radio :value="item.value" v-for="item in dict.sourceEnumList" :key="item.value">
          {{ item.label }}
        </a-radio>
      </a-radio-group>
    </page-form-item>
    <page-form-block>
      <a-col :span="operateWrapperSpan">
        <div class="page-title">结算信息</div>
      </a-col>
      <page-form-item label="是否分期" required size="1">
        <a-radio-group
          v-model="form.contractCarPurchaseEditVo.useInstallment"
          @change="onChangeUseInstallment"
          :options="dict.useInstallmentList"
        />
      </page-form-item>
      <!-- 车辆来源：自有、挂靠/托管、融资租赁 -->
      <template v-if="[1, 3, 4].includes(form.source)">
        <!-- 分期 -->
        <template v-if="form.contractCarPurchaseEditVo.useInstallment == 1">
          <page-form-item
            label="购车日期"
            labelTooltipContent="购车日期将作为购置税、过户费、运输费、保证金、手续费、首付的应付款日；如未填写，上述费用的应付款日取第一期付款日"
          >
            <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.purchaseCarDate" />
          </page-form-item>
          <page-form-item label="购置税">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.purchaseTax"
              :disabled="form.contractCarPurchaseEditVo.purchaseTaxFlag"
            />
          </page-form-item>
          <page-form-item label="首付">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.initialAmount"
              :disabled="form.contractCarPurchaseEditVo.initialAmountFlag"
            />
          </page-form-item>
          <page-form-item label="尾款">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.balanceAmount"
              :disabled="form.contractCarPurchaseEditVo.balanceAmountFlag"
            />
          </page-form-item>
          <page-form-item label="过户费">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.transferFee"
              :disabled="form.contractCarPurchaseEditVo.transferFeeFlag"
            />
          </page-form-item>
          <page-form-item label="运输费">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.transportationFee"
              :disabled="form.contractCarPurchaseEditVo.transportationFeeFlag"
            />
          </page-form-item>
          <page-form-item label="保证金">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.earnestMoney"
              :disabled="form.contractCarPurchaseEditVo.earnestMoneyFlag"
            />
          </page-form-item>
          <page-form-item label="手续费">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.serviceChargeFee"
              :disabled="form.contractCarPurchaseEditVo.serviceChargeFeeFlag"
            />
          </page-form-item>
          <page-form-item
            field="contractCarPurchaseEditVo.lnstalmentNum"
            label="期数"
            required
            :rules="[{ required: true, message: '请输入期数', trigger: 'blur' }]"
          >
            <i-input-number :precision="0" :min="1" v-model="form.contractCarPurchaseEditVo.lnstalmentNum" unit="期" />
          </page-form-item>
          <page-form-item
            field="contractCarPurchaseEditVo.amountPerPeriod"
            label="每期金额"
            required
            :rules="[{ required: true, message: '请输入每期金额', trigger: 'blur' }]"
          >
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.amountPerPeriod"
              :precision="2"
              :min="0.01"
              @change="handleAmountPerPeriodChange"
            />
          </page-form-item>
          <page-form-item
            field="contractCarPurchaseEditVo.lnstalmentFirstDate"
            label="第一期付款日"
            required
            :rules="[{ required: true, message: '请输入第一期付款日', trigger: 'blur' }]"
          >
            <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.lnstalmentFirstDate" />
          </page-form-item>
          <a-col :span="operateWrapperSpan">
            <div
              class="contract-operate-wrapper"
              :class="[!form.contractCarPurchaseEditVo.useInstallment ? 'contract-operate-wrapper2' : '']"
            >
              <div class="all-count"
                >合计：<span class="num">{{ countTotal }}元</span></div
              >
              <div class="contract-operate-content">
                <a-button class="view-payment-plan" type="primary" @click="viewPaymentPlanFn"> 查看付款计划 </a-button>
              </div>
            </div>
          </a-col>
        </template>
        <!-- 不分期 -->
        <template v-else>
          <page-form-item
            label="购车日期"
            labelTooltipContent="购车日期将作为购置金额、购置税、过户费、运输费、保证金、手续费的应付款日；如未填写，上述费用的应付款日取创建费用的日期。"
          >
            <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.purchaseCarDate" />
          </page-form-item>
          <page-form-item label="购置金额">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.purchaseAmount"
              :disabled="form.contractCarPurchaseEditVo.purchaseAmountFlag"
            />
          </page-form-item>
          <page-form-item label="购置税">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.purchaseTax"
              :disabled="form.contractCarPurchaseEditVo.purchaseTaxFlag"
            />
          </page-form-item>
          <page-form-item label="过户费">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.transferFee"
              :disabled="form.contractCarPurchaseEditVo.transferFeeFlag"
            />
          </page-form-item>
          <page-form-item label="运输费">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.transportationFee"
              :disabled="form.contractCarPurchaseEditVo.transportationFeeFlag"
            />
          </page-form-item>
          <page-form-item label="保证金">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.earnestMoney"
              :disabled="form.contractCarPurchaseEditVo.earnestMoneyFlag"
            />
          </page-form-item>
          <page-form-item label="手续费">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.serviceChargeFee"
              :disabled="form.contractCarPurchaseEditVo.serviceChargeFeeFlag"
            />
          </page-form-item>
        </template>
      </template>
      <!-- 车辆来源：借调（借入） -->
      <template v-else>
        <!-- 分期 -->
        <template v-if="form.contractCarPurchaseEditVo.useInstallment == 1">
          <page-form-item label="借入日期" labelTooltipContent="借入日期将作为首付的应付款日，如未填写，首付的应付款日取第一期付款日。">
            <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.purchaseCarDate" />
          </page-form-item>
          <page-form-item label="首付">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.initialAmount"
              :disabled="form.contractCarPurchaseEditVo.initialAmountFlag"
            />
          </page-form-item>
          <page-form-item label="尾款">
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.balanceAmount"
              :disabled="form.contractCarPurchaseEditVo.balanceAmountFlag"
            />
          </page-form-item>
          <page-form-item
            field="contractCarPurchaseEditVo.lnstalmentNum"
            label="期数"
            required
            :rules="[{ required: true, message: '请输入期数', trigger: 'blur' }]"
          >
            <i-input-number :precision="0" :min="1" v-model="form.contractCarPurchaseEditVo.lnstalmentNum" unit="期" />
          </page-form-item>
          <page-form-item
            field="contractCarPurchaseEditVo.amountPerPeriod"
            label="每期金额"
            required
            :rules="[{ required: true, message: '请输入每期金额', trigger: 'blur' }]"
          >
            <i-input-number
              v-model="form.contractCarPurchaseEditVo.amountPerPeriod"
              :precision="2"
              :min="0.01"
              @change="handleAmountPerPeriodChange"
            />
          </page-form-item>
          <page-form-item
            field="contractCarPurchaseEditVo.lnstalmentFirstDate"
            label="第一期付款日"
            required
            :rules="[{ required: true, message: '请输入第一期付款日', trigger: 'blur' }]"
          >
            <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.lnstalmentFirstDate" />
          </page-form-item>
          <a-col :span="operateWrapperSpan">
            <div
              class="contract-operate-wrapper"
              :class="[!form.contractCarPurchaseEditVo.useInstallment ? 'contract-operate-wrapper2' : '']"
            >
              <div class="all-count"
                >合计：<span class="num">{{ countTotal }}元</span></div
              >
              <div class="contract-operate-content">
                <a-button class="view-payment-plan" type="primary" @click="viewPaymentPlanFn"> 查看付款计划 </a-button>
              </div>
            </div>
          </a-col>
        </template>
        <!-- 不分期 -->
        <template v-else>
          <page-form-item
            label="借入日期"
            labelTooltipContent="借入日期将作为借调费（借入）的应付款日，如未填写，借调费（借入）的应付款日取生成费用的日期。"
          >
            <i-date-picker class="w-full" v-model="form.contractCarPurchaseEditVo.purchaseCarDate" />
          </page-form-item>
          <page-form-item label="借调费">
            <i-input-number
              :precision="2"
              :min="0"
              v-model="form.contractCarPurchaseEditVo.purchaseAmount"
              :disabled="form.contractCarPurchaseEditVo.purchaseAmountFlag"
            />
          </page-form-item>
        </template>
      </template>
    </page-form-block>
    <page-form-block>
      <a-col>
        <div class="page-title">合同信息</div>
      </a-col>
      <page-form-item
        label="合同编号"
        field="contractCarPurchaseEditVo.contractNo"
        :rules="{ match: /^[a-zA-Z0-9]{0,30}$/, message: '支持填写数字及字母，最多30位' }"
      >
        <i-input :max-length="30" v-model="form.contractCarPurchaseEditVo.contractNo" />
      </page-form-item>
      <page-form-item field="contractCarPurchaseEditVo.contractSignDate" label="合同开始日期">
        <i-date-picker
          class="w-full"
          :disabled-date="(date) => disabledDateFn(date, 'start')"
          v-model="form.contractCarPurchaseEditVo.contractSignDate"
        />
      </page-form-item>
      <page-form-item label="合同结束日期" field="contractCarPurchaseEditVo.contractEndDate">
        <i-date-picker
          class="w-full"
          :disabled-date="(date) => disabledDateFn(date, 'end')"
          v-model="form.contractCarPurchaseEditVo.contractEndDate"
        />
      </page-form-item>
      <page-form-item label="上传合同">
        <upload-attach class="upload-contract" v-model="form.contractCarPurchaseEditVo.contractFileId" :maxMB="20" />
      </page-form-item>
      <page-form-item label="借调同行" v-if="form.source == 2">
        <template #label-extra>
          <div>
            <img class="icon-img" src="@/assets/add.png" />
            <a class="a-link" @click="showaddTradeFn"> 添加同行 </a>
          </div>
        </template>
        <remote-select
          v-model="form.contractCarPurchaseEditVo.supplierId"
          :params="{ tradeNew }"
          placeholder="请选择"
          type="supplier_jdth"
        />
      </page-form-item>
      <page-form-item label="汽车销售" v-else>
        <a-select placeholder="请选择" v-model="form.contractCarPurchaseEditVo.supplierId" allow-clear>
          <a-option v-for="(item, index) in supplierLists" :key="index" :value="item.id"> {{ item.supplierName }}</a-option>
        </a-select>
        <a-button class="ml-2" type="primary" @click="showModalFn">
          <icon-plus />
          添加供应商
        </a-button>
      </page-form-item>
      <page-form-item label="收款账号">
        <i-input placeholder="请输入" :max-length="30" v-model="form.contractCarPurchaseEditVo.receiveAccount" />
      </page-form-item>
    </page-form-block>
    <!-- 查看付款计划 -->
    <car-payment-plan-modal ref="carPaymentPlanModalRef" @success="editCarPaymentPlanSuccessFn" />

    <a-modal
      v-model:visible="showModal"
      :mask-closable="false"
      title="新增"
      @cancel="onClose"
      @before-ok="onConfirm"
      width="45vw"
      unmount-on-close
    >
      <page-form :model="modalForm" div="true" class="page-form" ref="formRef" layout="vertical">
        <a-row class="typeName">
          <a-col :span="3.2" class="typeNameLabel">供应商类型：</a-col>
          <span class="typeNameValue">汽车销售</span>
        </a-row>
        <page-form-item required label="供应商名称" size="1" field="supplierName" :rules="{ required: true, message: '请输入供应商名称' }">
          <a-input v-model="modalForm.supplierName" style="width: 280px" :max-length="30" placeholder="请输入" allow-clear />
        </page-form-item>
      </page-form>
      <template #footer>
        <a-space>
          <a-button @click="onClose">关闭</a-button>
          <a-button type="primary" @click="onConfirm">确认</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 每期金额 -->
    <a-modal
      v-model:visible="showModalVisible"
      :mask-closable="false"
      @cancel="onCloseVisible"
      title="提示"
      @before-ok="onConfirmVisible"
      unmount-on-close
      simple
    >
      修改每期金额后，将同步更新付款计划中所有未付款的分期部分的金额。请确认是否修改？
      <template #footer>
        <a-space>
          <a-button @click="onCloseVisible">关闭</a-button>
          <a-button type="primary" @click="onConfirmVisible">确认</a-button>
        </a-space>
      </template>
    </a-modal>
    <!-- 新增同行 -->
    <AddTrade ref="addTradeRef" @refreshData="handleAddTradeOk" />
  </div>
</template>

<script setup name="CarManageFormCarSource">
  import { ref, inject, computed, watch, onMounted, nextTick } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { getCarDetail, editFindPayableListById, payablePreview, carPurchaseDetail } from '@/api/asset/car.js'
  import { getSupplierList } from '@/api/asset/maintenance'
  import carPaymentPlanModal from '../../components/car-payment-plan-modal.vue'
  import { addSupplier } from '@/api/asset/carInspect'
  import { useRoute } from 'vue-router'
  import AddTrade from '@/views/assets/operation/car-transfer/compoents/addTrade.vue'

  const showModal = ref(false)
  import dayjs from 'dayjs'
  const dict = inject('dict')
  const form = inject('form')
  const status = inject('status')
  const originDetail = inject('originDetail')
  const sourRef = inject('sourRef')
  const modalForm = ref({
    supplierName: '',
    supplierType: 3,
  })

  const showModalFn = () => {
    showModal.value = true
  }

  const addTradeRef = ref(null)
  const showaddTradeFn = () => {
    addTradeRef.value.show()
  }
  // 新增同行成功
  const tradeNew = ref(0)
  const handleAddTradeOk = (data) => {
    form.value.contractCarPurchaseEditVo.supplierId = data.id
    tradeNew.value++
  }

  const onClose = () => {
    showModal.value = false
    modalForm.value = {
      supplierName: '',
      supplierType: 3,
    }
  }

  const formRef = ref()
  const onConfirm = () => {
    formRef.value.validate((valid) => {
      if (!valid) {
        addSupplier({ ...modalForm.value })
          .then((res) => {
            console.log(res)
            Message.success(res.message)
            onClose()
            supplierList()
          })
          .catch((err) => {
            console.log(err)
          })
      }
    })
  }

  const label = computed(() => {
    let label = '合同总金额'
    switch (form.value.source) {
      case 2:
        label = '借调费'
        break
      default:
        label = '合同总金额'
        break
    }
    return label
  })

  const showModalVisible = ref(false)
  // 分期金额变化
  // 分期金额变化是否触发，默认是 true，当切换分期是否或者切换来源之后更改为 false
  const watchAmountPerPeriodChangeFlag = ref(true)
  // 上次输入的金额
  const lastInputValue = ref('')
  const handleAmountPerPeriodChange = (value) => {
    if (status.value == 'edit' && watchAmountPerPeriodChangeFlag.value) {
      // 上次输入的值
      const lastValue = lastInputValue.value || originDetail.value.contractCarPurchaseEditVo.amountPerPeriod
      // 和初始值不一样，触发校验
      if (value != lastValue) {
        showModalVisible.value = true
      } else {
        console.log('修改为初始值')
        // 记录本次输入的金额
        lastInputValue.value = value
      }
    }
  }
  // 询问弹窗点击确认（仅关闭弹窗）
  const onConfirmVisible = () => {
    showModalVisible.value = false
    // 记录本次输入的金额
    lastInputValue.value = form.value.contractCarPurchaseEditVo.amountPerPeriod
  }
  // 询问弹窗点击取消（关闭弹窗并还原分期金额）
  const onCloseVisible = () => {
    showModalVisible.value = false
    // 初始值
    const originValue = originDetail.value.contractCarPurchaseEditVo.amountPerPeriod
    // 存在上次输入价格，则回退成上次输入价格，否则回退成初始值
    form.value.contractCarPurchaseEditVo.amountPerPeriod = lastInputValue.value || originValue
  }

  // 是否是已付款账单
  const isPaid = ref(false)
  // 分期是否已付款
  const isPaidBorrowFee = ref(false)

  const route = useRoute()
  const routePrams = route.params
  // 62-购置税 63-过户费 64-运输费 65-保证金 66-手续费
  const isPaidObj = ref([])
  const useInstallmentFeeStatus = ref(false)
  onMounted(() => {
    supplierList()
    if (status.value == 'edit') {
      watch(
        () => originDetail.value,
        (newVal) => {
          if (newVal && Object.keys(newVal).length > 0) {
            console.log(newVal, form.value.contractCarPurchaseEditVo, 'originDetail')
            if (form.value.contractCarPurchaseEditVo.id) {
              carPurchaseDetail({ carId: routePrams.id, feeCategoryList: [0, 5, 6] }).then((res) => {
                const result = res.result
                if (result.carAssetFeeList) {
                  isPaidObj.value = result.carAssetFeeList.filter((item) => item.createNode !== 4 && item.payableNum > 0)
                  isPaidBorrowFee.value = isPaidObj.value.some((item) => {
                    return item.feeStatus == 1
                  })
                  isPaid.value = isPaidBorrowFee.value
                  useInstallmentFeeStatus.value = result.carAssetFeeList.some((item) => {
                    return item.feeStatus == 1
                  })
                  renderAllCount('isPaid')
                }
              })
              // 开启 source 监听
              startWatchSource()
            }
          }
        }
      )
    } else {
      // 开启 source 监听
      startWatchSource()
    }
  })

  // 合计
  const countTotal = ref(0)
  const initCount = (num) => {
    return Number(num) || 0
  }

  const onChangeUseInstallment = () => {
    if (useInstallmentFeeStatus.value) {
      Modal.confirm({
        title: '提示',
        hideCancel: true,
        maskClosable: false,
        escToClose: false,
        okText: '我已知晓',
        content: '存在已结算的费用，需将所有已付款or已收款的流水驳回，才能进行切换。',
        onOk: () => {
          form.value.contractCarPurchaseEditVo.useInstallment = originDetail.value.contractCarPurchaseEditVo.useInstallment
        }
      })
    } else {
      const { useInstallment, lnstalmentNum, amountPerPeriod, initialAmount, balanceAmount } = form.value.contractCarPurchaseEditVo
      if (useInstallment !== 1) {
        // 首付 + 尾款+ 每期金额*期数
        if (initialAmount || balanceAmount || (amountPerPeriod && lnstalmentNum)) {
          //购置金额
          // 借调费
          form.value.contractCarPurchaseEditVo.purchaseAmount =
            initCount(initialAmount) + initCount(balanceAmount) + initCount(lnstalmentNum) * initCount(amountPerPeriod)
        }
      }
      form.value.contractCarPurchaseEditVo.initialAmount = null
      form.value.contractCarPurchaseEditVo.balanceAmount = null
      form.value.contractCarPurchaseEditVo.lnstalmentNum = null
      form.value.contractCarPurchaseEditVo.amountPerPeriod = null
      form.value.contractCarPurchaseEditVo.lnstalmentFirstDate = null
      if (useInstallment == 1) {
        form.value.contractCarPurchaseEditVo.purchaseAmount = null
      }
      // 每期金额变化监听开关关闭
      watchAmountPerPeriodChangeFlag.value = false
    }
  }

  const supplierLists = ref([])
  const supplierList = () => {
    getSupplierList({ supplierType: 3, status: 1 }).then((res) => {
      supplierLists.value = res.result
    })
  }

  const disabledDateFn = (date, type) => {
    if (type == 'start') {
      let endDate = form.value.contractCarPurchaseEditVo.contractEndDate
      if (endDate) {
        return dayjs(date).startOf('day').valueOf() > dayjs(endDate).valueOf()
      } else {
        return false
      }
    } else {
      let startDate = form.value.contractCarPurchaseEditVo.contractSignDate
      if (startDate) {
        return dayjs(startDate).valueOf() > dayjs(date).startOf('day').valueOf()
      } else {
        return false
      }
    }
  }
  const renderAllCount = (isStatus) => {
    const {
      lnstalmentNum,
      amountPerPeriod,
      purchaseTax,
      initialAmount,
      balanceAmount,
      transportationFee,
      transferFee,
      earnestMoney,
      serviceChargeFee,
    } = form.value.contractCarPurchaseEditVo
    if ([1, 3, 4].includes(form.value.source)) {
      //合计 = 购置税 + 首付 + 尾款+ 过户费 + 运输费 + 保证金 + 手续费 + 每期金额*期数
      countTotal.value =
        initCount(purchaseTax) +
        initCount(initialAmount) +
        initCount(balanceAmount) +
        initCount(transferFee) +
        initCount(transportationFee) +
        initCount(earnestMoney) +
        initCount(serviceChargeFee)
    } else {
      // 合计 = 首付 + 尾款+ 每期金额*期数
      countTotal.value = initCount(initialAmount) + initCount(balanceAmount)
    }
    if (isPaid.value) {
      // 过滤出 feeStatus 为 1 的条目，表示已支付的部分
      const paidItems = isPaidObj.value.filter((item) => item.feeStatus === 1)
      // 已支付期数
      const paidCount = paidItems.length
      // 已支付总金额
      const paidTotal = paidItems.reduce((sum, item) => sum + (item.totalAmount || 0), 0)
      // 未支付期数
      const unpaidCount = (lnstalmentNum || 0) - paidCount
      // 未支付总金额
      let unpaidTotal = 0
      if (isStatus) {
        const unPaidItems = isPaidObj.value.filter((item) => item.feeStatus === 0)
        // 未支付总金额
        unpaidTotal = unPaidItems.reduce((sum, item) => sum + (item.totalAmount || 0), 0)
      } else {
        unpaidTotal = Math.abs(unpaidCount) * (amountPerPeriod || 0)
      }
      // 总金额
      const totalAmount = paidTotal + unpaidTotal
      countTotal.value = (countTotal.value + totalAmount).toFixed(2)
    } else {
      countTotal.value = (countTotal.value + initCount(lnstalmentNum) * initCount(amountPerPeriod)).toFixed(2)
    }
  }
  watch(
    () => form.value.contractCarPurchaseEditVo,
    () => {
      renderAllCount()
    },
    { immediate: true, deep: true }
  )
  const sourceConfig = {}
  // 监听 source
  const startWatchSource = () => {
    const watchInstance = watch(
      () => form.value.source,
      (newVal, oldVal) => {
        renderAllCount()
        console.log(newVal, oldVal, originDetail.value.source, 'source')
        if (status.value == 'new' || newVal === oldVal) {
          return
        }

        new Promise((resolve, reject) => {
          if (status.value == 'edit') {
            if (useInstallmentFeeStatus.value) {
              Modal.confirm({
                title: '车辆来源变更提示',
                simple: true,
                cancelText: '关闭',
                okText: '确认',
                content: '车辆来源变更，则已确认的费用及流水状态变更为已作废，是否确认变更来源？',
                onOk: () => {
                  resolve()
                },
                onCancel: () => {
                  reject()
                },
              })
            } else {
              Modal.confirm({
                title: '车辆来源变更提示',
                simple: true,
                cancelText: '关闭',
                okText: '确认',
                content: '车辆来源变更，原付款计划将自动删除，是否确认变更来源？',
                onOk: () => {
                  resolve()
                },
                onCancel: () => {
                  reject()
                },
              })
            }
          } else {
            resolve()
          }
        })
          .then(() => {
            if (status.value === 'edit') {
              watchAmountPerPeriodChangeFlag.value = false
              useInstallmentFeeStatus.value = false
              if (newVal !== originDetail.value.source) {
                isPaid.value = false
              } else {
                isPaid.value = isPaidBorrowFee.value
              }
              // 缓存
              if (oldVal) {
                console.log(sourceConfig[oldVal], 'sourceConfig: oldVal')
                sourceConfig[oldVal] = JSON.stringify(form.value.contractCarPurchaseEditVo)
              }
              if (sourceConfig[newVal]) {
                console.log(sourceConfig[newVal], 'sourceConfig: newVal')
                let temp = JSON.parse(sourceConfig[newVal])
                form.value.contractCarPurchaseEditVo = {
                  ...temp,
                }
              } else {
                form.value.contractCarPurchaseEditVo = {
                  useInstallment: 0, // 合同是否分期
                  lnstalmentNum: '',
                  initialAmount: '',
                  balanceAmount: '',
                }
              }
              console.log(sourceConfig, 'sourceConfig')
            }
          })
          .catch(() => {
            form.value.source = oldVal
            // 移除监听
            watchInstance()
            // 重新开启监听
            nextTick(() => {
              startWatchSource()
            })
          })
      }
    )
  }

  // 编辑付款账单完成
  const editCarPaymentPlanSuccessFn = () => {
    getCarDetail({ id: form.value.id }).then((res) => {
      // 最新的合同信息
      let newContractInfo = res.result.contractCarPurchaseEditVo

      // 更新合同信息
      // 当前组件的合同信息 form
      let contractInfo = form.value.contractCarPurchaseEditVo
      updateContractInfo(contractInfo, newContractInfo)
      // inject得到的编辑态下的 originDetail 初始值
      let originContractInfo = originDetail.value.contractCarPurchaseEditVo
      updateContractInfo(originContractInfo, newContractInfo)
    })
  }
  // 更新合同信息
  const updateContractInfo = (target, newInfo) => {
    Object.assign(target, newInfo)
  }

  const carPaymentPlanModalRef = ref()
  const viewPaymentPlanFn = () => {
    let contractInfo = form.value.contractCarPurchaseEditVo || {}
    let { amountPerPeriod, lnstalmentNum, lnstalmentFirstDate, contractSignDate, contractEndDate, purchaseCarDate } = contractInfo
    // 定义字段和对应的名称
    const requiredFields = [
      { value: amountPerPeriod, name: '每期金额' },
      { value: lnstalmentNum, name: '期数' },
      { value: lnstalmentFirstDate, name: '第一期付款日' },
    ]
    // 找到未填写的字段名称
    const missingFields = requiredFields.filter((field) => !field.value).map((field) => field.name)
    if (!amountPerPeriod) {
      sourRef.value.setFields({
        ['contractCarPurchaseEditVo.amountPerPeriod']: {
          status: 'error',
          message: '请输入每期金额',
        },
      })
    }
    if (!lnstalmentNum) {
      sourRef.value.setFields({
        ['contractCarPurchaseEditVo.lnstalmentNum']: {
          status: 'error',
          message: '请输入期数',
        },
      })
    }
    if (!lnstalmentFirstDate) {
      sourRef.value.setFields({
        ['contractCarPurchaseEditVo.lnstalmentFirstDate']: {
          status: 'error',
          message: '请输入第一期付款日',
        },
      })
    }
    if (missingFields.length > 0) {
      Message.warning({
        content: `请先填写${missingFields.join('、')}字段！`,
        closable: true,
        duration: 5000,
      })
    } else {
      let param = {}
      if ([1, 3, 4].includes(form.value.source)) {
        param = {
          purchaseTax: contractInfo.purchaseTax, //购置税
          initialAmount: contractInfo.initialAmount, //首付
          balanceAmount: contractInfo.balanceAmount, //尾款
          transferFee: contractInfo.transferFee, //过户费
          transportationFee: contractInfo.transportationFee, //运输费
          earnestMoney: contractInfo.earnestMoney, //保证金
          serviceChargeFee: contractInfo.serviceChargeFee, //手续费
          lnstalmentNum,
          lnstalmentAmount: amountPerPeriod,
          lnstalmentFirstDate,
          contractSignDate,
          contractEndDate,
          carSource: form.value.source,
          purchaseCarDate: contractInfo.purchaseCarDate, //购车、借入日期
        }
      } else {
        param = {
          initialAmount: contractInfo.initialAmount, //首付
          balanceAmount: contractInfo.balanceAmount, //尾款
          lnstalmentNum,
          lnstalmentAmount: amountPerPeriod,
          lnstalmentFirstDate,
          contractSignDate,
          contractEndDate,
          carSource: form.value.source,
          purchaseCarDate: contractInfo.purchaseCarDate, //购车、借入日期
        }
      }
      if (!contractInfo.id) {
        payablePreview(param).then((res) => {
          console.log(res)
          const result = res.result
          carPaymentPlanModalRef.value.open(result)
        })
      } else {
        param.id = contractInfo.id
        editFindPayableListById(param).then((res) => {
          console.log(res)
          const result = res.result
          carPaymentPlanModalRef.value.open(result, contractInfo.id)
        })
      }
    }
  }

  const operateWrapperSpan = computed(() => {
    // 是否分期
    let useInstallment = form.value.contractCarPurchaseEditVo.useInstallment
    // 合同类型
    let source = form.value.source
    if ([2, 4].includes(source)) {
      return useInstallment ? 24 : 16
    } else {
      return useInstallment ? 24 : 16
    }
  })
</script>

<style lang="less" scoped>
  .page-form {
    margin: 0;
    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
  .typeName {
    margin-bottom: 20px;
  }
  .typeNameLabel {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #4e5969;
    line-height: 22px;
    text-align: left;
  }
  .typeNameValue {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #1d2129;
  }
  .contract-operate-wrapper {
    width: 100%;
    height: 66px;
    margin-bottom: 20px;
    background: #f2f3f5;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    .contract-operate-content {
      .upload-contract {
        display: inline-block;
      }
      .view-payment-plan {
        margin-left: 16px;
      }
    }
  }
  .page-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #1d2129;
    margin-bottom: 14px;
  }
  .all-count {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #1d2129;
    text-align: left;
    font-style: normal;
    text-transform: none;
    .num {
      color: #1890ff;
    }
  }
  .icon-img {
    display: inline-block;
    width: 12px;
    height: 12px;
  }
  .a-link {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #1890ff;
    text-align: right;
    font-style: normal;
    text-transform: none;
    cursor: pointer;
  }
</style>
